package com.tsunami.auth.service.auth.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tsunami.auth.mapper.RoleMapper;
import com.tsunami.auth.service.auth.*;
import com.tsunami.authority.dto.auth.RolePageDTO;
import com.tsunami.authority.dto.auth.RoleSaveDTO;
import com.tsunami.authority.dto.auth.RoleUpdateDTO;
import com.tsunami.authority.entity.auth.Role;
import com.tsunami.authority.entity.auth.RoleOrg;
import com.tsunami.authority.entity.auth.User;
import com.tsunami.base.R;
import com.tsunami.utils.PageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author lx
 * @since 2021-09-23
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {

    @Autowired
    private IRoleOrgService roleOrgService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IRoleAuthorityService roleAuthorityService;
    @Autowired
    private IUserRoleService userRoleService;

    @Override
    public List<Role> findRoleByUserId(Long userId) {

        return baseMapper.findRoleByUserId(userId);
    }

    @Override
    public R selectPageList(RolePageDTO data) {
        Page<Role> pages = baseMapper.selectPageList(PageUtils.buildPage(),data);
        return R.ok().data(pages);
    }

    @Override
    public Boolean check(String code) {
        QueryWrapper param = new QueryWrapper();
        param.eq("code",code);
        return super.count(param)>0;
    }

    @Override
    public void saveRole(RoleSaveDTO data, Long userId) {
        Role role = new Role();
//        role.setTenantId();
        role.setName(data.getName());
        role.setCode(data.getCode());
        role.setDescribe(data.getDescribe());
        role.setStatus(data.getStatus());
        role.setReadonly(false);
        role.setCreateUser(userId);
        super.save(role);
        saveRoleOrg(userId,role,data.getOrgList());
    }

    @Override
    public void updateRole(RoleUpdateDTO data, Long id) {
        Role role = getById(data.getId());
//        role.setTenantId();
        role.setName(data.getName());
        role.setCode(data.getCode());
        role.setDescribe(data.getDescribe());
        role.setStatus(data.getStatus());
        role.setUpdateUser(id);
        super.updateById(role);
    }

    private void saveRoleOrg(Long userId, Role role, List<Long> orgList) {
        if(orgList!=null&&orgList.size()>0){
            List<RoleOrg> list = orgList.stream().map((orgId) ->
                    RoleOrg.builder()
                            .orgId(orgId)
                            .roleId(role.getId())
                            .createUser(userId)
                            .build())
                    .collect(Collectors.toList());
            roleOrgService.saveBatch(list);
        }
    }

    @Override
    public boolean removeById(List<Long> ids) {
        if(ids.isEmpty()){
            return true;
        }
        ids.forEach(roleId ->{
            List<User> userList = userService.findUserByRoleId(roleId,null);
            if(userList!=null&&userList.size()>0){
                userList.forEach(user -> {
                    //删除缓存中的用户资源
                });
            }
        });
        //删除主表tnm_auth_role数据
        super.removeByIds(ids);
        //删除tnm_auth_role_org关系表数据
        QueryWrapper roQuery = new QueryWrapper();
        roQuery.in("role_id",ids);
        roleOrgService.remove(roQuery);
        //删除tnm_auth_role_authority关系表数据
        QueryWrapper raQuery = new QueryWrapper();
        raQuery.in("role_id",ids);
        roleAuthorityService.remove(raQuery);
        //删除tnm_auth_user_role关系表数据
        QueryWrapper urQuery = new QueryWrapper();
        urQuery.in("role_id",ids);
        userRoleService.remove(urQuery);
        return true;
    }

    @Override
    public List<Long> findUserIdByCode(String[] codes) {
        return baseMapper.findUserIdByCode(codes);
    }

    @Override
    public List<Role> findRolesByStatus(String status) {
        QueryWrapper param = new QueryWrapper<>();
        param.eq("status",status);
        return baseMapper.selectList(param);
    }
}
